import Taro from '@tarojs/taro';
import { Iapi, ImyHeroData } from './interface';
import { Config } from './Config';

export const { windowHeight, windowWidth } = Taro.getSystemInfoSync();

export function request<T>(api: Iapi, data: any = {}) {
  const { url, method } = api;
  return new Promise<T>(function(resolve, reject) {
    // resolve('123');
    const myData = data; // api.method === 'POST' ? Qs.stringify(data) : data;
    const header =
      api.method === 'POST'
        ? {
            'Content-Type': 'application/x-www-form-urlencoded',
          }
        : {};

    Taro.request<T>({
      url: (api.hasHost ? '' : Config.baseURL) + url,
      method,
      data: myData,
      header,
      dataType: api.dataType || 'json',
    })
      .catch((error) => {
        console.log({ error });
        reject();
      })
      .then((callback) => {
        if (callback) {
          resolve(callback.data);
        } else {
          reject();
        }
      });
  });
}
export function uploadImage(api: Iapi, filePath: string, name: string = '') {
  const formData: Record<string, any> = {};
  return Taro.uploadFile({
    url: Config.baseURL + api.url,
    filePath,
    name,
    formData,
  });
}
